﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Text.RegularExpressions;
using NewsMine.Utilities;

namespace WebApp1
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public MvcApplication()
        {
            this.Error += new EventHandler(MvcApplication_Error);
            this.PreRequestHandlerExecute += new EventHandler(MvcApplication_PreRequestHandlerExecute);
            TempLogger.LogsBaseDirectory =  System.Web.Hosting.HostingEnvironment.MapPath("~\\logs\\");
        }

        void MvcApplication_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            bool IsProxyModeEnabled = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings.Get("IsProxyModeEnabled"));

            if (IsProxyModeEnabled == true)
                return;

            bool IsAdminPortal = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings.Get("IsAdminPortal"));

            if (IsAdminPortal == true)
                return;

            if (Request.Url.Host.ToLower() == "lookatnews.com"
                || Request.Url.Host.ToLower() == "test.lookatnews.com"
                )
            {
                Response.RedirectPermanent(Request.Url.Scheme + "://www.lookatnews.com" + Request.Url.PathAndQuery);
                return;
            }

            string[] oldSiteLanguages = { "english", "hindi", "kannada", "malayalam", "telugu", "tamil" };


            foreach (var lng in oldSiteLanguages)
            {
                if (Regex.IsMatch(Request.Url.AbsolutePath, "^(/" + lng + ").*", RegexOptions.IgnoreCase))
                {
                    Response.RedirectPermanent("/language/" + lng);
                    break;
                }

                if (Regex.IsMatch(Request.Url.AbsolutePath, "(/" + lng + "/).+(.aspx).*", RegexOptions.IgnoreCase))
                {
                    Response.RedirectPermanent("/language/" + lng);
                    break;
                }
            }

            if (Regex.IsMatch(Request.Url.AbsolutePath, "([a-zA-z-])(.aspx)", RegexOptions.IgnoreCase))
            {
                Response.RedirectPermanent("/");
            }

            if (Regex.IsMatch(Request.Url.AbsolutePath, ".*(/previous/).*", RegexOptions.IgnoreCase))
            {
                Response.RedirectPermanent("/");
            }

            if (Regex.IsMatch(Request.Url.AbsolutePath, ".*(/gadgets/newsgadget.aspx).*", RegexOptions.IgnoreCase))
            {
                Response.RedirectPermanent("/");
            }


            if (Regex.IsMatch(Request.Url.AbsolutePath, ".*(NewsSiteMap.aspx).*", RegexOptions.IgnoreCase))
            {
                Response.RedirectPermanent("/");
            }

            if (Regex.IsMatch(Request.Url.AbsolutePath, ".*(sitemap-000.xml).*", RegexOptions.IgnoreCase))
            {
                Response.RedirectPermanent("/urllist.txt");
            }



            ///sitemap-000.xml
            //NewsSiteMap.aspx
            ///gadgets/newsgadget.aspx
            //http://lookatnews.com


        }

        void MvcApplication_Error(object sender, EventArgs e)
        {
            Application_Error();
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {

            bool IsProxyModeEnabled = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings.Get("IsProxyModeEnabled"));

            if (IsProxyModeEnabled == true)
            {
                routes.MapRoute(
                  "NotFound",
                  "{*url}",
                  new { controller = "Home", action = "CatchAll" } // Parameter defaults
                );
                return;
            }

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
              "WebSiteInfo", // Route name
              "WebSiteInfo/{action}/{id}", // URL with parameters
              new { controller = "WebSiteInfo", action = "Index", id = UrlParameter.Optional } // Parameter defaults
          );

            routes.MapRoute(
            "Go", // Route name
            "Go/{id}", // URL with parameters
            new { controller = "Home", action = "Go", id = UrlParameter.Optional } // Parameter defaults
            );
            
            routes.MapRoute(
                  "fb", // Route name
                  "fb/{id}", // URL with parameters
                  new { controller = "Home", action = "fb", id = UrlParameter.Optional } // Parameter defaults
              );


            routes.MapRoute(
             "Search", // Route name
             "Search/{q}/{page}", // URL with parameters
             new { controller = "Home", action = "Search", q = UrlParameter.Optional, page = "1.html" } // Parameter defaults
         );

             routes.MapRoute(
             "AdminSearch", // Route name
             "AdminSearch/{q}/{page}", // URL with parameters
             new { controller = "Home", action = "AdminSearch", q = UrlParameter.Optional, page = "1.html" } // Parameter defaults
         );

            

            routes.MapRoute(
           "RssSearch", // Route name
           "RssSearch/{q}/{page}", // URL with parameters
           new { controller = "Home", action = "RssSearch", q = UrlParameter.Optional, page = "1.html" } // Parameter defaults
       );

            routes.MapRoute(
            "Source", // Route name
            "Source/{id}/{page}", // URL with parameters
            new { controller = "Home", action = "Source", id = UrlParameter.Optional, page = "1.html" } // Parameter defaults
        );

            routes.MapRoute(
           "Language", // Route name
           "Language/{id}/{page}", // URL with parameters
           new { controller = "Home", action = "Language", id = UrlParameter.Optional, page = "1.html" } // Parameter defaults
       );


            routes.MapRoute(
            "Category", // Route name
            "Category/{id}/{page}", // URL with parameters
            new { controller = "Home", action = "Category", id = UrlParameter.Optional, page = "1.html" } // Parameter defaults
        );

            routes.MapRoute(
          "Topic", // Route name
          "Topic/{id}/{page}", // URL with parameters
          new { controller = "Home", action = "Topic", id = UrlParameter.Optional, page = "1.html" } // Parameter defaults
      );

            
            routes.MapRoute(
          "Channel", // Route name
          "Channel/{id}/{page}", // URL with parameters
          new { controller = "Home", action = "Topic", id = UrlParameter.Optional, page = "1.html" } // Parameter defaults
            );

            routes.MapRoute(
               "Default", // Route name
               "{controller}/{action}/{id}/{page}", // URL with parameters
               new { controller = "Home", action = "Default", id = UrlParameter.Optional, page = "1.html" } // Parameter defaults
           );



            //routes.MapRoute(
            //  "NotFound",
            //  "{*url}",
            //  new { controller = "Home", action = "CatchAll"} // Parameter defaults
            //);


        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_Error()
        {
            //todo:
            //for now this is not used.
            // in future if there is a need to handle the exceptions in application level, we just need to use this code.

            return;

            Exception exception = Server.GetLastError();
            this.Response.Clear();

            HttpException httpException = exception as HttpException;

            if (httpException != null)
            {
                string action;
                Response.StatusCode = 200;
                Response.SuppressContent = true;
                switch (httpException.GetHttpCode())
                {
                    case 404:
                        // page not found
                        Response.Write("404 error");
                        break;
                    case 500:
                        // server error
                        Response.Write("500 error");

                        break;
                    default:
                        Response.Write("default error");

                        break;
                }
            }
        }
    }
}